//
//  InputViewModel.swift
//  JonCalculator
//
//  Created by shiyanjun on 2023/1/13.
//

import Foundation

class InputViewModel: ObservableObject {
    // 输入的数字1
    private var number1: Double = 0.0
    // 输入的数字2
    private var number2: Double = 0.0
    
    // 输入的运算符
    @Published var inputOperator: String = ""
    // 执行的运算结果
    private var calcuResult: Double = 0.0
    // 显示运算结果
    @Published var showResult: Double = 0.0
    
    func inputNumber(inputNumber: Double) {
        if self.inputOperator == "" {
            self.number1 = self.number1 * 10.0 + inputNumber
            self.showResult = self.number1
        } else {
            self.number2 = self.number2 * 10.0 + inputNumber
            self.showResult = self.number2
        }
    }
    
    func inputOperator(inputOperator: String) {
        if inputOperator == "+" || inputOperator == "-" {
            self.inputOperator = inputOperator
            calculateResult()
        } else if inputOperator == "x" {
            self.inputOperator = inputOperator
            // TODO 乘法待优化
            calculateResult()
        } else if inputOperator == "/" {
            self.inputOperator = inputOperator
            // TODO 乘法待优化
            calculateResult()
        }
    }
    
    func calculateResult() {
        switch self.inputOperator {
        case "+":
            calculateAdd(number1: number1, number2: number2)
        case "-":
            calculateSubtract(number1: number1, number2: number2)
        case "x":
            calculateMultiply(number1: number1, number2: number2)
        case "/":
            calculateDivide(number1: number1, number2: number2)
        default:
            return
        }
    }
    
    // 加法运算
    func calculateAdd(number1: Double, number2: Double) {
        self.calcuResult = number1 + number2

        self.number1 = self.calcuResult
        self.number2 = 0.0
        self.showResult = self.number1
    }
    
    // 减法运算
    func calculateSubtract(number1: Double, number2: Double) {
        self.calcuResult = number1 - number2
        
        self.number1 = self.calcuResult
        self.number2 = 0.0
        self.showResult = self.number1
    }
    
    // 乘法运算
    func calculateMultiply(number1: Double, number2: Double) {
        self.calcuResult = number2 == 0.0 ? number1 * 1.0 : number1 * number2
        // TODO 乘法待优化
        self.number1 = self.calcuResult
        self.number2 = 0.0
        self.showResult = self.number1
    }
    
    // 除法运算
    func calculateDivide(number1: Double, number2: Double) {
        self.calcuResult = number2 == 0.0 ? number1 / 1.0 : number1 / number2
        // TODO 除法待优化
        self.number1 = self.calcuResult
        self.number2 = 0.0
        self.showResult = self.number1
    }
    
    func clear() {
        self.number1 = 0.0
        self.number2 = 0.0
        self.inputOperator = ""
        self.calcuResult = 0.0
        self.showResult = 0.0
    }
}
